<?php
namespace app\admin\controller;
use app\admin\logic\MarkLogic;
use think\Db;
use app\service\CouponService;
use think\Request;

class Mark extends Base
{
	public function _initialize()
	{
		// 调用父类前置方法
		parent::_initialize();

		// 登录校验
		$this->IsLogin();
	}

	/**
	 * 优惠券列表
	 */
	public function index(Request $request)
	{
        if ($request->isAjax()){
            $list = Db::name('mark')->where('delete_time',0)->order('id desc')->select();
            $num = Db::name('mark')->where('delete_time',0)->count();
            $statuss = [0=>'未使用',1=>'已使用'];
            if (!empty($list)){
                foreach ($list as $kk=>$vv){
                    $list[$kk]['status'] = $statuss[$vv['is_use']];
                    $list[$kk]['add_time_time'] = date('Y-m-d H:i',$vv['add_time']);
                    if ($vv['upd_time']>0){
                        $list[$kk]['upd_time_time'] = date('Y-m-d H:i',$vv['upd_time']);
                    }else{
                        $list[$kk]['upd_time_time'] = '-';

                    }
                    if ($vv['user_id']>0){
                        $user = Db::name('user')->where('id',$vv['user_id'])->value('nickname');
                        $list[$kk]['user_name'] = $user;
                    }else{
                        $list[$kk]['user_name'] = '-';
                    }
                }
                $result['code'] = 0;
                $result['msg'] = "请求成功";
                $result['data'] = $list;
                $result['count'] = $num;
            }

            echo json_encode($result);
            die;
        }
        return $this->fetch();
	}

    public function addmark(Request $request){
        if ($request->isAjax()){
            $param = $request->param();
            $tm = [];
            if ($param['num'] >1){
                for ($i = 0;$i<$param['num'];$i++){
                    $tm[$i] = MarkLogic::makekey();
                }
                $all = [];
                foreach ($tm as $k=>$value){
                    $all[$k]['key'] = $value;
                    $all[$k]['add_time'] = time();
                    $all[$k]['money'] = $param['money'];
                    $resu = Db::name('mark')->insert($all[$k]);
                }

            }else{
                $result = MarkLogic::makekey();


                $insert['key'] = $result;
                $insert['add_time'] = time();
                $insert['money'] = $param['money'];
                $resu = Db::name('mark')->insertGetId($insert);
            }


            if ($resu){
                $echo['code'] = 0;
                $echo['msg'] = '生成成功';
            }else{
                $echo['code'] = -1;
                $echo['msg'] = '生成失败';
            }
            echo json_encode($echo);die;
        }

        return $this->fetch();
    }
}